<template>
  <div>
    <!-- 顶部 -->
    <div class="addresss">
      <div class="shouhuo">
        <!-- <span class="topone">购物车</span> -->
        <van-icon name="location-o" size="14" />
        <span class="toptwo" @click="toaddress()">收货地址({{ address }})</span>
      </div>
    </div>
    <!--end  -->
   

    <!-- 购物车为空时 -->
    <van-empty v-if="carts.length === 0" description="还没有商品，快去添加吧~">
      <van-button
        @click="toshopping()"
        round
        color="linear-gradient(to right, #ff9000, #ff5000)"
        class="bottom-button"
        >逛一逛</van-button
      >
    </van-empty>
    <!-- end -->

    <!-- 购物车有商品时 -->
    <div class="noempty" v-else>
      <div class="carts">
        <van-swipe-cell v-for="cart in carts" :key="cart.id">
          <van-card :num="cart.number" :desc="cart.specs">
            <template #thumb>
              <van-checkbox
                @change="checkedOne()"
                v-model="cart.checked"
                checked-color="#ee0a24"
              ></van-checkbox>
              <img :src="cart.banner" />
            </template>

            <template #title>
              <div class="btext">
                <b>{{ cart.name }}</b>
              </div>
            </template>

            <template #price>
              <span style="color: red">￥{{ cart.price }}</span>
            </template>

            <template #num>
              <van-button
                class="reduce"
                @click="reduceNum(cart.id)"
                size="mini"
                plain
                hairline
                type="primary"
                color="#ccc"
                >-</van-button
              >
              <span class="pronum">{{ cart.number }}</span>
              <van-button
                @click="addNum(cart.id)"
                size="mini"
                plain
                hairline
                type="primary"
                color="#ccc"
                >+</van-button
              >
            </template>
            <template #bottom>
              <!-- 小数点处理：1.强制保存小数点后几位2.不用js提供的计算方法，自己封装函数写 -->
              <br />
              <div class="tips">
                小计：<span>￥{{ cart.subtotal }}</span>
                <van-count-down :time="time" format= " 活动剩余时间： HH 时 mm 分 ss 秒" />           
              </div>
            </template>
            <!-- <template #price-top>
            <span @click="del(cart.id)" class="remove">×</span>
          </template>                  -->
          </van-card>
          <!-- 右侧删除按钮 -->
          <template #right>
            <van-button
              @click="del(cart.id)"
              type="danger"
              class="delete-button"
            >
              <van-icon name="delete-o" size="20" />
              <p>删除</p>
            </van-button>
          </template>
        </van-swipe-cell>
      </div>
      <!-- 底部结算部分 -->
      <div class="jiesuan">
        <div class="settle">
          <van-checkbox
            @click="checkedAll()"
            v-model="checkAll"
            checked-color="#ee0a24"
            >
            <p style="color: rgb(255 253 253)">全选</p>
            </van-checkbox>
          <div class="text">
            <p>合计：{{ totalPrice }}</p>
            <!-- <p>已优惠：￥6</p> -->
            <p>{{ discount }}</p>
          </div>
          <van-button round color="#ff5000" plain>去结算（{{ totalNum }}）</van-button>
        </div>
      </div>

    </div>
    <!-- end -->
  </div>
</template>


<script>
import { getCookie } from "@/utils/cookie";
import { getCartsPro, editCart, delCart, getDefaultAddr } from "@/request";
import { Checkbox, CheckboxGroup } from "vant";

import { Button } from "vant";
import { operate } from "@/utils/math";
import { Icon } from "vant";
import Vue, { del } from "vue";
import { Card } from "vant";

import { Dialog } from "vant";
import { Toast } from "vant";

import { Popup } from "vant";

import { AddressList } from "vant";
import { SwipeCell } from "vant";
import { Empty } from "vant";

import { NoticeBar } from 'vant';
import { CountDown } from 'vant';

Vue.use(CountDown);


Vue.use(NoticeBar);

Vue.use(Empty);

Vue.use(SwipeCell);
Vue.use(AddressList);

Vue.use(Popup);

Vue.use(Toast);

Vue.use(Icon);

Vue.use(Button);
Vue.use(Checkbox);
Vue.use(CheckboxGroup);

Vue.use(Card);
export default {
  data() {
    return {
      carts: [],
      checkAll: false,
      show: false,
      address: "",
      time: 30*60 * 60 * 1000,
    };
  },
  created() {
    // 判断用户是否登录，没有就进行登录
    var username = getCookie("username");
    if (!username) {
      localStorage.setItem("url", "/cart");
      this.$router.push("my/login");
    }
    getCartsPro().then((data) => {
      this.carts = data.map((item) => {
        item.created = false;
        item.subtotal = operate(item.price, item.number, "*");
        return item;
      });
    });

    // 获取默认地址，将地址显示在页面
    getDefaultAddr().then((data) => {
      console.log(data);
      if (data.code === 1) {
        this.address = data.data.name + "," + data.data.address;
      } else {
        this.address = "请添加地址";
      }
    });
  },

  
  computed: {
    // 统计价钱
    totalPrice() {
      var carts = this.carts.filter((item) => item.checked);
      var n = 0;
      carts.forEach((item) => {
        n += item.subtotal;
      });
      return n;
    },
    // 统计数量
    totalNum() {
      var carts = this.carts.filter((item) => item.checked);
      var n = 0;
      carts.forEach((item) => {
        n += item.number;
      });
      return n;
    },
    // 优惠劵
    discount() {
      var carts = this.carts.filter((item) => item.checked);
      var n = 0;
      carts.forEach((item) => {
        n += item.subtotal;
      });
      if (n>=100&&n<=200) {
        return "劵优惠：￥10";
      }else if(n>200&&n<=400){
        return "劵优惠：￥30";
      }

    },
    
  },
  methods: {
    // 数量+
    addNum(id) {
      //当前商品数量自增，先获取当前商品数量
      var cart = this.carts.find((item) => item.id === id);
      cart.number++;
      //重新计算小计
      cart.subtotal = operate(cart.price, cart.number, "*");
      editCart(cart).then((data) => {
        console.log(data);
      });
    },
    // 数量-
    reduceNum(id) {
      var cart = this.carts.find((item) => item.id === id);
      //变1无效
      if (cart.number <= 1) {
        return;
      } else {
        cart.number--;
        cart.subtotal = operate(cart.price, cart.number, "*");
        editCart(cart).then((data) => {
          console.log(data);
        });
      }

      // 变0删除
      //  cart.number--
      //  if(cart.number===0){
      //      var index=this.carts.findIndex(item =>item.id===id)
      //     this.carts.splice(index,1)
      //     delCart(id).then(data =>{

      //     })
      //  }else{

      //     cart.subtotal=operate(cart.price, cart.number, '*')
      //     editCart(cart).then(data =>{
      //     console.log(data);
      // })
      //  }
    },

    // 全选框
    checkedAll() {
      this.carts.forEach((item) => {
        item.checked = this.checkAll;
      });
    },
    // 单选框
    checkedOne() {
      // var bool =this.carts.every(item=>item.checked)
      // this.checkAll=bool

      this.checkAll = this.carts.every((item) => item.checked);
    },
    // 删除
    del(id) {
      Dialog.confirm({
        title: "购物车删除",
        message: "你真的要删除这个商品吗？",
      })
        // 真的要删除
        .then(() => {
          var index = this.carts.findIndex((item) => item.id === id);
          this.carts.splice(index, 1);
          delCart(id).then((data) => {
            Toast.success(data.msg);
          });
        })
        // 不要删除
        .catch(() => {
          Toast.success("已取消");
        });
    },

    // 页面跳转
    toaddress() {
      this.$router.push("/cart/address");
    },
    toshopping() {
      this.$router.push("/types");
    },
  },
};
</script>

<style scoped>

/* 顶部部分样式 */
.shouhuo {
  display: block;
  padding: 8px;
  border-top-left-radius: 11px;
  border-top-right-radius: 12px;
  background-image: linear-gradient(to right, #ff9000, #ff5000);
  
}
.toptwo {
  font-size: 12px;
  color: #ffffff;
}
.topone {
  font-weight: bold;
  font-size: 18px;
}

/* 购物车为空时样式 */
.bottom-button {
  width: 160px;
  height: 40px;
}


/* 购物车样式 */

/* 商品图片样式 */
.carts img {
  width: 95px;
  height: 93px;
  margin-left: 26px;
  margin-top: 12px;
}

/* 复选框样式 */
.van-card__thumb {
  width: 130px;
}
.carts .van-checkbox {
  position: absolute;
  left: -8px;
  top: 64%;
  transform: translateY(-50%);
}

/* 商品名样式 */
.btext {
  width: 182px;
  margin-top: 10px;
}

/* 价格样式 */
.van-card__price {
  display: inline-block;
  color: #323233;
  font-weight: 500;
  font-size: 12px;
  padding-top: 1px;
}

/* 按钮样式 */
.van-card__num {
  margin-right: -6px;
  margin-top: 7px;
}
.van-card__num .van-button {
  width: 20px;
  height: 20px;
  font-size: 18px;
  vertical-align: top;
}
.pronum {
  font-size: 16px;
  border: 1px solid rgb(229 219 219 / 93%);
  padding: 0.5px 10px;
}

/* 小计样式 */
.tips {
  padding-top: 1px;
}

/* 倒计时样式 */
.van-count-down {
    color: #f94d05;
    font-size: 1px;
    line-height: 20px;
    width: 184px;
    padding-top: 1px;
}

/* 产品描述（/斤） */
.van-card__desc.van-ellipsis {
  width: 150px;
  padding-top: 5px;
}

/* 右侧删除按钮 */
.delete-button {
  width: 50px;
  height: 125px;
}
.delete-button p {
  text-align: center;
  font-size: 13px;
}
button.delete-button.van-button.van-button--danger.van-button--normal {
  padding: 5px;
}


/* .remove {
  position: absolute;
  top: 7%;
  transform: translateY(-50%);
  right: -17px;
  font-size: 20px;
  padding: 10px;
} */

/* 结算部分样式 */
.jiesuan {
  position: fixed;
  bottom: 50px;
  left: 0;
  width: 100%;
  background-image: linear-gradient(to right, #ff9000, #ff5000);
  border-radius: 10px;
}
.settle {
  display: flex;
  justify-content: space-between;
  padding: 10px 20px;
  align-items: center;
  color: rgb(255, 255, 255);
}
/* .van-checkbox__label {
  margin-left: 8px;
  color: rgb(255 253 253);
  line-height: 20px;
} */
.settle .text {
  flex: 1;
  padding-left: 20px;
}
.settle .text p {
  padding: 0;
  margin: 0;
}





/* .van-card__content > div:first-child {
  margin-right: 170px;
} */





</style>